<template>
    <div ref="scroll">
        <div class="mt-4" v-for="item in todoList" :key="item.id">
            <div v-show="!item.__edit__" style="border: 1px solid #d1d9e0">
                <div slot="header" class="clearfix flex items-center relative">
                    <el-alert v-if="item.isComplete" title="已完成" type="success" show-icon :closable="false">
                    </el-alert>
                    <el-alert v-else title="未完成" type="warning" show-icon :closable="false">
                    </el-alert>
                    <el-dropdown style="position: absolute !important; right: 16px" trigger="click">
                        <i class="el-icon-more"></i>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item @click.native="onCompleteTodo(item, true)" v-if="!item.isComplete"
                                icon="el-icon-circle-check">完成</el-dropdown-item>
                            <el-dropdown-item @click.native="onCompleteTodo(item, false)" v-else-if="item.isComplete"
                                icon="el-icon-circle-close">未完成</el-dropdown-item>
                            <el-dropdown-item @click.native="onEdit(item)" icon="el-icon-edit">编辑</el-dropdown-item>
                            <el-dropdown-item @click.native="onDeleteTodo(item)"
                                icon="el-icon-delete">删除</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </div>
                <div @change="onChange(item, $event)" v-markdown="item.description" class="vditor-reset px-8 py-2">
                </div>
            </div>

            <div v-show="item.__edit__">
                <div class="todo-edit"></div>
                <div class="text-right mt-2">
                    <el-button @click="item.__edit__ = false" type="warning">取消</el-button>
                    <el-button :loading="item.loading" @click="onTodoSave(item)" type="success">保存</el-button>
                </div>
            </div>
        </div>
        <div class="mt-8">
            <h3 class="font-bold text-xl">添加新事项</h3>
        </div>
        <div class="mt-2" ref="newPost"></div>
        <div class="mt-2 text-right mb-16">
            <el-button :loading="createLoading" @click="onCreateTodo" type="success">创建</el-button>
        </div>
    </div>
</template>

<script>
import SideTitle from "@/components/SideTitle/index.vue";
import { del, onMounted, ref, set, nextTick, defineComponent } from '@vue/composition-api';
import Vditor from 'vditor';
import 'vditor/dist/index.css'
import { getTask, completeTask } from '@/api/task'
import { getTaskTodoList, createTodo, editTodo, deleteTodo, completeTodo } from '@/api/taskTodo'
import { Message } from 'element-ui';
import router from '../../../router';
import "@/lute.min.js";
const lute = window.Lute.New();
export default defineComponent({
    directives: {
        markdown: {
            // 指令的定义
            inserted: function (el, binding) {
                el.innerHTML = lute.Md2HTML(binding.value)
                Array.from(el.getElementsByClassName('vditor-task')).forEach(item => {
                    item.children[0].removeAttribute('disabled')

                })
            },
            update(el, binding) {
                el.innerHTML = lute.Md2HTML(binding.value)
                Array.from(el.getElementsByClassName('vditor-task')).forEach(item => {
                    item.children[0].removeAttribute('disabled')


                })
            }
        }
    },
    setup() {

        const todoList = ref([])
        const newPost = ref(null)
        let contentEditor = null
        onMounted(() => {
            contentEditor = new Vditor(newPost.value, {
                toolbar: [
                    'emoji',
                    'headings',
                    'bold',
                    'italic',
                    'strike',
                    'link',
                    '|',
                    'list',
                    'ordered-list',
                    'check',
                    'outdent',
                    'indent',
                    '|',
                    'quote',
                    'line',
                    'code',
                    'inline-code',
                    'insert-before',
                    'insert-after',
                    '|',
                    'upload',
                    'record',
                    'table',
                    '|',
                    'undo',
                    'redo',
                    '|',
                    'edit-mode',
                    // 'content-theme',
                    // 'code-theme',
                    'export',
                    {
                        name: 'more',
                        toolbar: [
                            'fullscreen',
                            'both',
                            'preview',
                            'info',
                            'help',
                        ],
                    }],
                minHeight: 500,
                width: 1400,
                preview: {
                    maxWidth: 1100
                },
                toolbarConfig: {
                    // pin: true,
                },
                upload: {
                    filename(name) {
                            return name
                        },
                    url: import.meta.env.VITE_UPLOAD_URL
                },
                cache: {
                    enable: false,
                },
                cdn: import.meta.env.VITE_BASE,
                after: () => {
                    // contentEditor.setValue('hello, Vditor + Vue!')
                },
            })
        })

        function onChange(row, e) {
            if (e.target.checked) {
                e.target.setAttribute('checked', 'checked')
            } else {
                e.target.removeAttribute('checked')
            }


            row.description = lute.HTML2Md(e.currentTarget.innerHTML)
            editTodo({
                id: row.id,
                description: row.description
            }).then(res => {
            }).finally(() => {
            })
        }

        const editorMap = {}


        const loading = ref(false)
        function fetchData() {
            loading.value = true
            console.log(router.currentRoute.query)
            getTaskTodoList({
                taskId: router.currentRoute.query.taskId,
            }).then(res => {
                todoList.value = res.data
            }).finally(() => {
                loading.value = false
            })
        }
        fetchData()
        const createLoading = ref(false)
        function onCreateTodo() {
            if (!contentEditor.getValue()) {
                return Message.warning('请输入事项')
            }
            createLoading.value = true
            createTodo({
                taskId: router.currentRoute.query.taskId,
                description: contentEditor.getValue(),
                isComplete: false
            }).then(res => {
                const dto = res.data
                todoList.value.push(dto)
                contentEditor.setValue('')
            }).finally(() => {
                createLoading.value = false
            })
        }

        function onCompleteTodo(row, isComplete) {
            set(row, 'loading', true)
            completeTodo({
                id: row.id,
                isComplete
            }).then(res => {
                row.isComplete = isComplete
            }).finally(() => {
                del(row, 'loading')
            })
        }

        function onDeleteTodo(row) {
            set(row, 'loading', true)
            deleteTodo({
                id: row.id,
            }).then(res => {
                const index = todoList.value.findIndex(item => item.id === row.id)
                todoList.value.splice(index, 1)
            }).finally(() => {
                del(row, 'loading')
            })
        }

        function onTodoSave(row) {
            set(row, 'loading', true)
            const newVal = editorMap[row.id].getValue()
            editTodo({
                id: row.id,
                description: newVal
            }).then(res => {
                del(row, '__edit__', true)
                nextTick(() => {
                    row.description = newVal
                })
            }).finally(() => {
                del(row, 'loading', true)
            })

        }
        const title = ref('')
        const description = ref('')
        const isTaskComplete = ref(false)
        function fetchTask() {
            console.log(router.currentRoute.query.taskId)
            getTask({
                taskId: router.currentRoute.query.taskId
            }).then(res => {
                title.value = res.data.title
                description.value = res.data.description
                isTaskComplete.value = 3 === res.data.status
            })
        }
        fetchTask()

        const completeTaskLoading = ref(false)
        function onCompleteTask() {
            completeTaskLoading.value = true
            completeTask({
                taskId: router.currentRoute.query.taskId
            }).then(() => {
                isTaskComplete.value = true
            }).finally(() => {
                completeTaskLoading.value = false
            })
        }

        return {
            title,
            description,
            todoList,
            loading,
            newPost,
            editorMap,
            onChange,
            createLoading,
            onCreateTodo,
            onCompleteTodo,
            onDeleteTodo,
            onTodoSave,

            completeTaskLoading,
            onCompleteTask,
            isTaskComplete

        }
    },
    methods: {
        onEdit(row) {
            this.$set(row, '__edit__', true)
            this.$nextTick(() => {
                const index = this.todoList.findIndex(item => item.id === row.id)
                console.log(index, this.$refs.scroll.getElementsByClassName('todo-edit'))
                const editor = new Vditor(this.$refs.scroll.getElementsByClassName('todo-edit')[index], {
                    toolbar: [
                        'emoji',
                        'headings',
                        'bold',
                        'italic',
                        'strike',
                        'link',
                        '|',
                        'list',
                        'ordered-list',
                        'check',
                        'outdent',
                        'indent',
                        '|',
                        'quote',
                        'line',
                        'code',
                        'inline-code',
                        'insert-before',
                        'insert-after',
                        '|',
                        'upload',
                        'record',
                        'table',
                        '|',
                        'undo',
                        'redo',
                        '|',
                        'edit-mode',
                        // 'content-theme',
                        // 'code-theme',
                        'export',
                        {
                            name: 'more',
                            toolbar: [
                                'fullscreen',
                                'both',
                                'preview',
                                'info',
                                'help',
                            ],
                        }],
                    // height: '500px',
                    minHeight: 500,
                    width: 1400,
                    preview: {
                     maxWidth: 1100
                    },
                    toolbarConfig: {
                        // pin: true,
                    },
                    upload: {
                        filename(name) {
                            return name
                        },
                    url: import.meta.env.VITE_UPLOAD_URL
                },
                cache: {
                    enable: false,
                },
                cdn: import.meta.env.VITE_BASE,
                    after: () => {
                        editor.setValue(row.description)
                    },
                })
                this.editorMap[row.id] = editor
            })
        },

    }
})

</script>


<style scoped>
.custom-card>>>.el-card__header {
    padding: 0 !important;
}
</style>